package com.lagou.client;

import com.lagou.common.constant.Constants;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RpcConsumer {

    //创建线程池对象
    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static UserClientHandler userClientHandler;

    //1.创建一个代理对象 providerName：UserService#sayHello are you ok?
    public Object createProxy(final Class<?> serviceClass,final String providerName){
        //借助JDK动态代理生成代理对象
        return  Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //（1）调用初始化netty客户端的方法
                if (userClientHandler == null) {
                    initClient();
                }
                userClientHandler.setPara(providerName+args[0]);
                // 去服务端请求数
                return executor.submit(userClientHandler).get();
            }
        });


    }



    //2.初始化netty客户端
    public static  void initClient() throws InterruptedException {
        userClientHandler = new UserClientHandler();
        ServiceDiscovery serviceDiscovery = new ServiceDiscovery(Constants.REGISTRY_ADDRESS);
        String serverAddress = serviceDiscovery.discover();
        String host = "";
        int port = 0;
        if (serverAddress!=null) {
            String[] array = serverAddress.split(":");
            if (array!=null && array.length==2) {
                host = array[0];
                port = Integer.parseInt(array[1]);
            }
        }
        System.out.println("从zookeeper注册中心获取到的服务地址为：" + host + ";端口号为：" + port);

        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(userClientHandler);
                    }
                });

        ChannelFuture sync = bootstrap.connect(host, port).sync();
        if (sync.isSuccess()) {
            System.out.println("成功连接到服务，服务地址为：" + host + ";端口号为：" + port);
        }
    }
}
